package com.xy.smartsms.service.carrierparam;

import android.content.Context;
import android.text.TextUtils;

import com.xy.smartsms.constant.NetConstant;
import com.xy.smartsms.db.carrierparam.BlackListManager;
import com.xy.smartsms.db.carrierparam.OnlineConfigManager;
import com.xy.smartsms.db.carrierparam.entity.BlackListItem;
import com.xy.smartsms.db.carrierparam.entity.OnlineConfigItem;
import com.xy.smartsms.util.Log;
import com.xy.smartsms.util.ThreadManager;

import org.json.JSONArray;
import org.json.JSONObject;

import java.util.HashMap;
import java.util.Map;

import cn.com.xy.sms.sdk.Iservice.XyCallBack;
import cn.com.xy.sms.sdk.db.entity.SysParamEntityManager;
import cn.com.xy.sms.sdk.util.BaseRunnable;

/**
 * Created by kangwenbo on 2017/3/1.
 */

public class UpdateBlackListRunnable extends BaseRunnable {

    private final String TAG = "UpdateBlackListRunnable";
    private Context mContext;
    public static final String LOCAL_BLACKLIST_VERSION = "EMBED_BLACKLIST_VERSION";
    private Map<String, Object> queryMap;
    private String mCNum;
    private String mIccid;

    /**
     * @param cNum  短信中心号
     * @param iccid
     * @return
     */
    public void requestData(Context context, String cNum, String iccid) {
        mContext = context;
        mCNum = cNum;
        mIccid = iccid;
        ThreadManager.executeRunnableByPool(ThreadManager.NUMBER_UPDATE_CARRIER, this);
    }


    @Override
    protected boolean inQueryInterval() {
        if (OnlineConfigManager.getInstance().getIntervalTime(OnlineConfigItem.FLAG_BLACK_LIST_LAST_VERSION) < System.currentTimeMillis())
            return false;
        return true;
    }

    private void initData() {
        String version = SysParamEntityManager.getStringParam(mContext, LOCAL_BLACKLIST_VERSION);
        if (TextUtils.isEmpty(version))
            version = "1";
        queryMap = new HashMap<String, Object>();
        queryMap.put("version", version);
        queryMap.put("cNum", mCNum);
        queryMap.put("iccid", mIccid);
    }

    @Override
    public void execute() {
        initData();
        UpdateCarrierParamService.updateDataByNet(NetConstant.REQUEST_URL_ESCAPEITEM, queryMap, new HashMap<String, String>(), new XyCallBack() {
            @Override
            public void execute(Object... objects) {

                try {
                    JSONObject jb = UpdateCarrierParamService.isValidOfData(objects);
                    if (jb == null) {
                        UpdateCarrierParamService.updateOnlineConfig(OnlineConfigItem.FLAG_BLACK_LIST_LAST_VERSION, OnlineConfigItem.STATUS_FAIL);
                        return;
                    }
                    analysisData(jb);
                    UpdateCarrierParamService.updateOnlineConfig(OnlineConfigItem.FLAG_BLACK_LIST_LAST_VERSION, OnlineConfigItem.STATUS_SUCCESS);
                } catch (Throwable t) {
                    Log.e(TAG, "execute", t);
                    UpdateCarrierParamService.updateOnlineConfig(OnlineConfigItem.FLAG_BLACK_LIST_LAST_VERSION, OnlineConfigItem.STATUS_FAIL);
                }

            }
        });
    }

    private void analysisData(JSONObject jsonObject) {
        try {
            if (jsonObject.has("datas")) {
                JSONArray jsonArray = jsonObject.optJSONArray("datas");
                for (int i = 0; i < jsonArray.length(); i++) {
                    JSONObject jb = jsonArray.optJSONObject(i);
                    BlackListItem blackListItem = new BlackListItem();
                    blackListItem.setPhone(jb.optString("number"));
                    blackListItem.setFuncBitwise(jb.optLong("limit"));
                    blackListItem.setDisplayBitwise(jb.optLong("display"));
                    blackListItem.setVersion(jb.optString("version"));
                    int status = jb.optInt("status");
                    blackListItem.setLastUpdateStatus(status);
                    if (status == -1) {
                        //delete
                        BlackListManager.getInstance().delete(blackListItem);
                    } else {
                        //update or insert
                        blackListItem.setLastUpdateTime(System.currentTimeMillis());
                        BlackListManager.getInstance().updateOrInsert(blackListItem);
                    }
                }
                if (jsonObject.has("version"))
                    SysParamEntityManager.setParam(LOCAL_BLACKLIST_VERSION, jsonObject.optString("version"));
            }
        } catch (Throwable t) {
            Log.e(TAG, "", t);
        }


    }
}
